<?php

/**
 * Simple JSON-RPC interface.
 */
namespace app\common\service;

class TrxService 
{

	//生成地址
	public function getAddress($password){
		$tron = new \IEXBase\TronAPI\Tron();
		$response = $tron->createAccount();
		return [
			'hex_address'=>$response->getAddress(),
			'address'=>$response->getAddress(true),
			'private_key'=>$response->getPrivateKey(),
			'public_key'=>$response->getPublicKey(),
		];
	}


	//转账trx
	public function transTrx($data){
		$tron = new \IEXBase\TronAPI\Tron();
		$tron->setPrivateKey($data['private_key']);
		return $tron->sendTransaction($data['to'],$data['amount'],null,$data['hex_address']);
	}


	//代币转账 trx-usdt
	public function transUsdt($data,$contract_address='TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){
		$tron = new \IEXBase\TronAPI\Tron();
		$tron->setPrivateKey($data['private_key']);
		$trxUsdt = $tron->contract($contract_address);
		$trxUsdt->setFeeLimit($data['gas_price']);
		return $trxUsdt->transfer($data['to'],$data['amount'],$data['from']);
	}

	//代币转账
	public function transDb($data,$contract_address='TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){
		$tron = new \IEXBase\TronAPI\Tron();
		$tron->setPrivateKey($data['private_key']);
		$trxUsdt = $tron->contract($contract_address);
		$trxUsdt->setFeeLimit($data['gas_price']);
		return $trxUsdt->transfer($data['to'],$data['amount'],$data['from']);
	}

	//获取trx余额
	public function getTrxBalance($address){
		$tron = new \IEXBase\TronAPI\Tron();
		return $tron->getBalance($address);
	}

	//获取trx代币余额
	public function getUsdtBalance($address,$contract_address='TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){
		$tron = new \IEXBase\TronAPI\Tron();
		return $tron->contract($contract_address)->balanceOf($address);
	}

	//获取代币余额
	public function getDbBalance($address,$contract_address='TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){
		$tron = new \IEXBase\TronAPI\Tron();
		return $tron->contract($contract_address)->balanceOf($address);
	}
	//设置密码
	public function setPassword($password){
		return md5(md5($password.'one').'two');
	}

	//私钥导入
	public function importByPrivateKey($private_key){
		$tron = new \IEXBase\TronAPI\Tron();
		$response = $tron->importByPrivateKey($private_key);
		return [
			'hex_address'=>$response->getAddress(),
			'address'=>$response->getAddress(true),
			'private_key'=>$response->getPrivateKey(),
			'public_key'=>$response->getPublicKey(),
		];
	}
}
